package com.gxkj.movie.filters;


import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;
/**
 * 由于需要配置顺序，迁移到WebConfig中配置了
 */
//@WebFilter(urlPatterns = "/*", filterName = "traceIdFilter")
public class TraceIdFilter implements Filter {
    public static final String TRACE_KEY = "traceId";
    private static final Logger logger = LoggerFactory.getLogger(TraceIdFilter.class);



    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        //先从param里取，没有的话从header里取，还没有的话再创建
        String traceId = request.getParameter("TRACE_ID");
        if (StringUtils.isBlank(traceId)){
            traceId = httpServletRequest.getHeader("X-Request-Id");
        }

        if (StringUtils.isBlank(traceId)){
            traceId = UUID.randomUUID().toString().replace("-", "");
        }

        MDC.put( TRACE_KEY, traceId);

        try{
            chain.doFilter(request, response);

        }catch (Exception e){

            throw  e;
        }finally {
            MDC.remove(TRACE_KEY);
        }




    }

    @Override
    public void destroy() {

    }
}